package com.mirror.tk.core.sms.work.impl;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.mirror.tk.core.sms.exception.SMSException;
import com.mirror.tk.core.sms.work.BaseSmsSendServiceImpl;

public class IhuyiSmsSendServiceImplImpl extends BaseSmsSendServiceImpl {

	@XmlRootElement(name = "SubmitResult", namespace = "http://106.ihuyi.cn/")
	@XmlAccessorType(XmlAccessType.FIELD)
	public static class SubmitResult {
		
		@XmlElement(namespace = "http://106.ihuyi.cn/")
		private String code;
		@XmlElement(namespace = "http://106.ihuyi.cn/")
		private String msg;
		@XmlElement(namespace = "http://106.ihuyi.cn/")
		private String smsid;

		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}

		public String getSmsid() {
			return smsid;
		}

		public void setSmsid(String smsid) {
			this.smsid = smsid;
		}
	}

	private String url;
	private String account;
	private String password;
	private Unmarshaller unmarshaller;

	public IhuyiSmsSendServiceImplImpl() {

		try {
			unmarshaller = JAXBContext.newInstance(SubmitResult.class).createUnmarshaller();
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	protected Map<String, String> builderParam(String phone, String msg) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("account", account);
		paramMap.put("password", password);
		paramMap.put("mobile", phone);
		paramMap.put("content", msg);
		return paramMap;
	}

	@Override
	protected void responseHandler(String result) throws SMSException {
		logger.debug("response data:{}", result);
		try {
			SubmitResult submitResult = (SubmitResult) unmarshaller.unmarshal(new StringReader(result));
			if (false == "2".equals(submitResult.getCode())) {
				throw new SMSException(submitResult.getCode(), submitResult.getMsg(), "sms send error " + submitResult.getMsg());
			}
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	protected String getInterfaceAddress() {
		return url;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
}

